# Decompiled with PyLingual (https://pylingual.io)
# Internal filename: hkex.py
# Bytecode version: 3.12.0rc2 (3531)
# Source timestamp: 2024-05-26 22:43:38 UTC (1716763418)

import uiautomator2 as u2
import time
import sys
import os
import json
from lxml import etree
from PIL import Image
from loguru import logger
import pytesseract
import traceback
import subprocess
from PIL import ImageOps
import aircv as ac
import pyttsx3
import random
import datetime
import sqlite3
from multiprocessing import Lock, Value, Process
import tkinter as tk
from tkinter import ttk
cjjj = 0

def Device_connect(device):
    try:
        device_id = device[10]
        logname = device[0] + '_' + device_id + '_log.txt'
        logger.add(logname, encoding='utf-8')
        time.sleep(1)
        logger.info('准备连接设备 %s ...' % device_id)
        d = u2.connect(device_id)
        title = ''
        logger.info(f'连接设备 {device_id} ({device[0]}) 成功!')
        MultiDevice(d, device)
    except:
        logger.exception('连接设备 %s 失败！' % device_id)

def select_hkex_type(d, future='小恒指期货'):
    """type: 恒指期货 or 小恒指期货\n    """  # inserted
    d.click(250, 217)
    if future == '恒指期货':
        time.sleep(1)
        d.click(149, 323)
        time.sleep(0.5)
    if future == '小恒指期货':
        time.sleep(1)
        d.click(150, 360)
        time.sleep(0.5)

def MultiDevice(d, device):
    device_id = device[10]
    db = sqlite3.connect('db.sqlite3')
    cursor = db.cursor()
    user_id = '13300000109'
    now_position = {'direction': '买入', 'future': '小恒指期货', 'num': 0}
    pass
    strategy_list = [{'round': 1, 'future': '小恒指期货', 'num': 1}, {'round': 2, 'future': '小恒指期货', 'num': 2}, {'round': 3, 'future': '恒指期货', 'num': 1}, {'round': 4, 'future': '恒指期货', 'num': 2}, {'round': 5, 'future': '恒指期货', 'num': 4}, {'round': 6, 'future': '恒指期货', 'num': 8}]
    now_round = 1
    rounds_count = 1
    direction_list = ['买入', '卖出']
    direction = random.choice(direction_list)
    is_open_market = False
    engine = pyttsx3.init()
    engine.setProperty('voice', 'com.microsoft.speech.platform.voice.SynthesizerVoice')
    engine.setProperty('rate', 130)
    engine.setProperty('volume', 1)
    device_info = d.device_info
    sys_settings = device_info.get('sys_settings')
    if sys_settings:
        logger.critical(f"当前模拟器标题为:{sys_settings.get('title')}")
    pid = d.app_start('uni.UNI97D49FD', wait=True)
    time.sleep(random.randint(6, 10))
    d.screenshot().save('full_%s.png' % device_id)
    imsrc = ac.imread('full_%s.png' % device_id)
    imobj = ac.imread('denglu.png')
    pos = ac.find_template(imsrc, imobj, 0.8)
    if pos is None:
        logger.warning(f'{device[0]} 当前已经登录')
    else:  # inserted
        logger.warning(f'{device[0]} 当前没有登录')
        if device[2] == '模拟':
            d.click(381, 334)
            time.sleep(1)
            d.click(237, 462)
        else:  # inserted
            d.click(381, 334)
            time.sleep(1)
            d.click(281, 519)
        time.sleep(1)
        d.click(333, 408)
        time.sleep(0.5)
        d.set_fastinput_ime(True)
        d.clear_text()
        d.send_keys(device[0], True)
        time.sleep(0.5)
        d.press('back')
        d.click(321, 494)
        time.sleep(0.5)
        d.set_fastinput_ime(True)
        d.clear_text()
        d.send_keys(device[1], True)
        time.sleep(0.5)
        d.press('back')
        time.sleep(1)
        d.click(268, 590)
    time.sleep(2)
    if d(resourceId='android:id/alertTitle').exists:
        d(resourceId='android:id/button1').click()
        logger.info(f'{device[0]} : 点击了关闭弹窗  知道了 按钮')
    time.sleep(1)
    if d(text='确认').exists():
        logger.info(f'{device[0]} : 点击了关闭弹窗 确认 按钮')
        d(text='确认').click()
    time.sleep(1)
    if d(text='交易').exists():
        logger.info(f'{device[0]} 点击了交易 按钮')
        d(text='交易').click()
    time.sleep(0.5)
    d.click(276, 800)
    if d(text='持仓').exists():
        logger.info(f'{device[0]} 点击了持仓 按钮')
        d(text='持仓').click()
    time.sleep(1)
    pass
    cjjj = 0
    if d(text='持仓').exists():
        logger.info(f'{device[0]} 点击了持仓 按钮')
        d(text='持仓').click()
        d.screenshot().save('full_%s.png' % device_id)
        imsrc = ac.imread('full_%s.png' % device_id)
        imobj = ac.imread('pingcang_ico.png')
        pos = ac.find_template(imsrc, imobj, 0.8)
        if pos is None:
            now_position = {'direction': '买入', 'future': '小恒指期货', 'num': 0}
            logger.warning(f'{device_id} 当前没有持仓，判断最后一手交易')
            time.sleep(1)
            now_round = pytesseract_lastorder(d, device)
            logger.warning(f"{device[0]}  {time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())}  当前从第{rounds_count}轮,第{now_round}次开始")
            time.sleep(1)
        else:  # inserted
            rounds_count, now_round, cjjj = pytesseract_noworder(d, device, cursor)
            time.sleep(1)
    else:  # inserted
        logger.error(f"{device[0]}  {device_id}  {time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())}  未能打开持仓界面，操作失败，请检查")
        starttime = datetime.datetime.strptime(str(datetime.datetime.now().date()) + ' 16:15:00', '%Y-%m-%d %H:%M:%S')
        endtime = datetime.datetime.strptime(str(datetime.datetime.now().date()) + ' 17:15:00', '%Y-%m-%d %H:%M:%S')
        starttime1 = datetime.datetime.strptime(str(datetime.datetime.now().date()) + ' 02:40:00', '%Y-%m-%d %H:%M:%S')
        endtime1 = datetime.datetime.strptime(str(datetime.datetime.now().date()) + ' 09:15:00', '%Y-%m-%d %H:%M:%S')
        starttime2 = datetime.datetime.strptime(str(datetime.datetime.now().date()) + ' 12:00:00', '%Y-%m-%d %H:%M:%S')
        endtime2 = datetime.datetime.strptime(str(datetime.datetime.now().date()) + ' 13:00:00', '%Y-%m-%d %H:%M:%S')
        while True:
            try:
                if starttime <= datetime.datetime.now() and datetime.datetime.now() <= endtime or (starttime1 <= datetime.datetime.now() and datetime.datetime.now() <= endtime1) or (starttime2 <= datetime.datetime.now() and datetime.datetime.now() <= endtime2):
                    is_open_market = False
                    print(f"{device[0]}  {device_id}  {time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())}  当前已休市，开市后继续...[09:15-12:00,13:00-16:30,17:15-03:00]")
                else:  # inserted
                    is_open_market = True
        except:
            pass  # postinserted
        logger.exception('设备 %s    %s 执行发生错误！' % (device_id, device[0]))
        time.sleep(random.randint(5, 15))
            else:  # inserted
                try:
                    if is_open_market:
                        now_second = datetime.datetime.now().second
                        new = pytesseract_new(d, device_id)
                        fdyk = pytesseract_fdyk(d, device_id)
                        pcyk = pytesseract_pcyk(d, device_id)
                        zje = pytesseract_total_amount(d, device_id)
                        sxf = pytesseract_commission_amount(d, device_id)
                        print(f"{device[0]}  {device_id}  {time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())}  指数：{new}  成交均价：{cjjj}  账户金额：{zje}  浮动盈亏：{fdyk}  平仓盈亏:{pcyk}  手续费:{sxf}  当前第{rounds_count}轮，第{now_round}次")
                        cursor.execute('update user set device_status=\'在线\',user_floating=?,user_now_amount=?,edittime=?,rounds_count=?,round=?,user_total_amount=?,user_commission=?,user_price_index=? where user_login_id=?', (fdyk, pcyk, time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()), rounds_count, now_round, zje, sxf, cjjj, device[0]))
                        db.commit()
                        now_minute = datetime.datetime.now().minute
                        if now_minute % 10 == 0 and now_second == 1:
                            d(text='K线').click()
                            time.sleep(3)
                            d(text='交易').click()
        except:
            pass  # postinserted
        logger.exception('数据获取失败')

def getUserInfo(d, device_id):
    """获取当前登录客户信息"""  # inserted
    d(text='我的').click()
    time.sleep(1)
    d.drag(324, 718, 330, 460, 0.1)
    time.sleep(0.5)
    d.click(250, 850)
    time.sleep(3)
    uiObjectBox = [353, 251, 533, 289]
    sj = pytesseract.image_to_string(d.screenshot().crop(uiObjectBox), lang='chi_sim')
    sj = sj.replace('\n', '')
    uiObjectBox = [396, 332, 534, 369]
    name = pytesseract.image_to_string(d.screenshot().crop(uiObjectBox), lang='chi_sim')
    name = name.replace('\n', '')
    logger.info(f'当前登录用户：{name}，手机:{sj}')
    d.click(38, 71)
    time.sleep(1)
    d.click(375, 915)

def setZhiYing(d, device_id, ying=0, sun=0):
    """\n    设置止盈止损\n    ying：止盈  -1 默认设置\n    sun: 止损\n    """  # inserted
    time.sleep(0.5)
    d.click(276, 800)
    time.sleep(0.5)
    d(text='持仓').click()
    d.screenshot().save('full_%s.png' % device_id)
    imsrc = ac.imread('full_%s.png' % device_id)
    imobj = ac.imread('pingcang_ico.png')
    pos = ac.find_template(imsrc, imobj)
    if pos is None:
        logger.error(f'{device_id} 当前没有持仓，无法设置止盈止损。')
        return
    d.drag(135, 746, 408, 748, 0.05)
    d.drag(135, 746, 408, 748, 0.05)
    d.drag(135, 746, 408, 748, 0.05)
    d.drag(474, 732, 241, 732, 0.05)
    d.drag(474, 732, 241, 732, 0.05)
    pass
    d.click(506, 604)
    time.sleep(1)
    logger.info('打开了添加止盈止损页面')
    if d(text='编辑').exists():
        logger.warning('存在止盈止损设置，进行编辑')
        d(text='编辑').click()
        time.sleep(1)
        d.xpath('//*[@text=\"pages/transaction/dataList[13]\"]/android.view.View[5]/android.view.View[1]/android.view.View[3]/android.view.View[2]').set_text(str(sun))
        d.xpath('//*[@text=\"pages/transaction/dataList[13]\"]/android.view.View[5]/android.view.View[1]/android.view.View[4]/android.view.View[2]').set_text(str(ying))
        time.sleep(2)
        d.click(281, 510)
    else:  # inserted
        logger.warning('进行止盈止损添加')
        d(text='添加').click()
        if ying == (-1) or sun == (-1):
            time.sleep(1)
            d.click(281, 510)
            logger.info('按默认值添加')
            time.sleep(1)
        else:  # inserted
            d.xpath('//*[@text=\"pages/transaction/dataList[13]\"]/android.view.View[5]/android.view.View[1]/android.view.View[3]/android.view.View[2]').set_text(str(sun))
            d.xpath('//*[@text=\"pages/transaction/dataList[13]\"]/android.view.View[5]/android.view.View[1]/android.view.View[4]/android.view.View[2]').set_text(str(ying))
    uiObjectBox = [99, 152, 197, 180]
    tesseract_config = '--oem 3 --psm 6 outputbase'
    d.screenshot().crop(uiObjectBox).save('cjjj_%s.png' % device_id)
    cjjj = pytesseract.image_to_string(d.screenshot().crop(uiObjectBox), config=tesseract_config)
    cjjj = cjjj.replace('\n', '')
    time.sleep(1)
    d.click(33, 67)
    time.sleep(2)
    d.drag(74, 757, 501, 748, 0.05)
    time.sleep(0.5)
    d.click(245, 730)
    time.sleep(0.5)
    return float(cjjj)

def setNumber(d, device_id, num):
    """设置手数"""  # inserted
    try:
        uiObjectBox = [141, 266, 231, 302]
        tesseract_config = '--oem 3 --psm 6 outputbase'
        d.screenshot().crop(uiObjectBox).save('shoushu_%s.png' % device_id)
        shoushu = pytesseract.image_to_string(d.screenshot().crop(uiObjectBox), config=tesseract_config)
        shoushu = shoushu.replace('\n', '')
        shoushu = int(shoushu)
        if shoushu < num:
            print(f'当前手数{shoushu}小于要操作手数{num},准备点击')
            for i in range(num - shoushu):
                d.click(249, 286)
                time.sleep(0.3)
        if shoushu > num:
            print(f'当前手数{shoushu}大于要操作手数{num},准备点击')
            for i in range(shoushu - num):
                d.click(122, 286)
                time.sleep(0.3)
    except:
        logger.exception('设置手数失败！！')
        time.sleep(0.3)

def pytesseract_PlaceOrder(d, device_id, direction='买入', future='小恒指期货', num=1):
    """\n    下单\n    direction:下单方向  买入，卖出\n    future_type:期货类型  恒指期货，小恒指期货\n    """  # inserted
    try:
        d.screenshot().save('full_%s.png' % device_id)
        imsrc = ac.imread('full_%s.png' % device_id)
        imobj = ac.imread('mairu.png')
        pos = ac.find_template(imsrc, imobj, 0.8)
        if pos is None:
            logger.error(f'{device_id}  当前不在交易页面，下单失败！')
            return False
        logger.info(f'准备下单 {direction} {future} {num}手...')
        select_hkex_type(d, future)
        setNumber(d, device_id, num)
        time.sleep(2)
        if direction == '买入':
            d(text='买入').click()
        if direction == '卖出':
            d(text='卖出').click()
        time.sleep(2)
        while True:
            time.sleep(1)
            if d(text='确认').exists:
                msg = pytesseract_ok(d, device_id)
                logger.warning(f'{msg}')
                if msg is not None and '委托提示' in msg:
                    d(text='确认').click()
                    logger.info(f'{device_id},委托提示已提交！')
                    break
        if False:
            time.sleep(1)
            if d(text='确认').exists:
                msg = pytesseract_ok(d, device_id)
                logger.warning(f'{msg}')
                if msg is not None:
                    if '已成交' in msg:
                        d(text='确认').click()
                        logger.info(f'{device_id},{msg},委托交易已确认成交！')
                    else:  # inserted
                        if '该品种已限制开仓' in msg or '委托失败' in msg:
                            logger.error('当前不允许下单！或者委托失败！')
                            d(text='确认').click()
                            time.sleep(random.randint(10, 30))
                            return False
    except:
        pass  # postinserted
    logger.exception('设备 %s 执行发生错误！' % device_id)
    return (-1)
                    else:  # inserted
                        if '尝试使用移动网络' in msg or '下单失败' in msg:
                            d(text='确认').click()
                            logger.error('相同ip同时下单，暂停一下,稍后再试')
                            time.sleep(random.randint(1, 10))
                            return False
                    else:  # inserted
                        if '单笔下单量超过最大限定值' in msg:
                            d(text='确认').click()
                            logger.error('此账号只允许下单一手。')
                            return False
        time.sleep(2)
        logger.info('设置止盈止损')
        cjjj = setZhiYing(d, device_id, (-1), (-1))
        return cjjj

def pytesseract_pingcang(d, device_id):
    """操作手动平仓"""  # inserted
    d.screenshot().save('full_%s.png' % device_id)
    imsrc = ac.imread('full_%s.png' % device_id)
    imobj = ac.imread('pingcang_ico.png')
    pos = ac.find_template(imsrc, imobj)
    print(pos)
    if pos is None:
        return 0
    x, y = pos['result']
    d.click(x, y)
    while True:
        time.sleep(1)
        if d(text='确认').exists:
            time.sleep(1)
            msg = pytesseract_ok(d, device_id)
            logger.warning(f'平仓委托提示信息：{msg}')
            if msg is not None and '委托提示' in msg:
                d(text='确认').click()
                logger.info(f'{device_id},委托提示已提交！')
                break
    if False:
        time.sleep(1)
        if d(text='确认').exists:
            time.sleep(1)
            msg = pytesseract_ok(d, device_id)
            logger.warning(f'{msg}')
            if msg is not None and '已成交' in msg:
                d(text='确认').click()
                logger.info(f'{device_id},委托交易已成交！')
                break

def pytesseract_ok(d, device_id):
    """交易成功弹窗提示"""  # inserted
    try:
        uiObjectBox = [45, 305, 492, 568]
        d.screenshot().crop(uiObjectBox).save('msg_%s.png' % device_id)
        img = Image.open('msg_%s.png' % device_id)
        custom_config = '--oem 3 --psm 6 -l chi_sim'
        content = pytesseract.image_to_string(img, config=custom_config)
        content = content.replace('\n', '')
        logger.warning(f'{device_id} :    ：{content}')
        return content
    except:
        logger.exception('设备 %s 执行发生错误！' % device_id)
        return ''

def pytesseract_noworder(d, device, cursor):
    """识别当前持仓信息"""  # inserted
    
    device_id = device[10]
    strategy_list = [{'round': 1, 'future': '小恒指期货', 'num': 1}, {'round': 2, 'future': '小恒指期货', 'num': 2}, {'round': 3, 'future': '恒指期货', 'num': 1}, {'round': 4, 'future': '恒指期货', 'num': 2}, {'round': 5, 'future': '恒指期货', 'num': 4}, {'round': 6, 'future': '恒指期货', 'num': 8}]
    now_round = 1
    rounds_count = 1
    d(text='持仓').click()
    time.sleep(1)
    d.drag(135, 746, 408, 748, 0.05)
    d.drag(135, 746, 408, 748, 0.05)
    d.drag(135, 746, 408, 748, 0.05)
    time.sleep(1)
    uiObjectBox = [91, 583, 303, 625]
    d.screenshot().crop(uiObjectBox).save('chicang0_%s.png' % device[0])
    img = Image.open('chicang0_%s.png' % device[0])
    content = pytesseract.image_to_string(img, lang='chi_sim')
    content = content.replace('\n', '')
    future = content.replace(' ', '')
    direction = ''
    if '卖' in future:
        direction = '卖出'
    if '买' in future:
        direction = '买入'
    if 'MHI' in future:
        future = '小恒指期货'
    if 'HSI' in future:
        future = '恒指期货'
    d.drag(496, 732, 245, 732, 0.05)
    uiObjectBox = [234, 583, 394, 625]
    d.screenshot().crop(uiObjectBox).save('chicang2_%s.png' % device[0])
    img = Image.open('chicang2_%s.png' % device[0])
    tesseract_config = '--oem 3 --psm 6 outputbase'
    content = pytesseract.image_to_string(img, config=tesseract_config)
    cjjj = content.replace('\n', '')
    cjjj = float(cjjj)
    logger.warning(f'{device[0]} :   成交均价 ：{cjjj}')
    uiObjectBox = [398, 583, 469, 625]
    d.screenshot().crop(uiObjectBox).save('chicang3_%s.png' % device[0])
    img = Image.open('chicang3_%s.png' % device[0])
    tesseract_config = '--oem 3 --psm 6 outputbase'
    content = pytesseract.image_to_string(img, config=tesseract_config)
    ccsl = content.replace('\n', '')
    logger.warning(f'{device[0]} :   持仓数量 ：{ccsl}')
    now_position = {'direction': direction, 'future': future, 'num': int(ccsl), 'index': cjjj}
    for item in strategy_list:
        if now_position['future'] == item['future'] and now_position['num'] == item['num']:
            logger.warning(f"{device[0]}  {time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())}  当前已有持仓为：{now_position},第{now_round}次")
            cursor.execute('SELECT * FROM hsiplus where user_id=? and trade_date=? ORDER BY id DESC limit 1;', (device[0], time.strftime('%Y-%m-%d', time.localtime())))
            row = cursor.fetchone()
            if row is not None:
                logger.info(f"{device[0]}  {device[10]}  {time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())} 当日最后记录为 {row[4]}轮，第{row[5]}次，{row[6]} {row[7]} {row[8]} 手 {row[9]}")
                rounds_count = row[4]
            if now_round == 1:
                rounds_count = rounds_count + 1
            d.drag(109, 721, 335, 721, 0.05)
            d.click(223, 769)
            return (rounds_count, now_round, cjjj)

def pytesseract_lastorder(d, device):
    """解析最后成交的一单数据"""  # inserted
    try:
        strategy_list = [{'round': 1, 'future': '小恒指期货', 'num': 1}, {'round': 2, 'future': '小恒指期货', 'num': 2}, {'round': 3, 'future': '恒指期货', 'num': 1}, {'round': 4, 'future': '恒指期货', 'num': 2}, {'round': 5, 'future': '恒指期货', 'num': 4}, {'round': 6, 'future': '恒指期货', 'num': 8}]
        d(text='持仓').click()
        time.sleep(1)
        d(text='成交').click()
        time.sleep(5)
        d.drag(135, 746, 408, 748, 0.05)
        d.drag(135, 746, 408, 748, 0.05)
        d.drag(135, 746, 408, 748, 0.05)
        time.sleep(1)
        uiObjectBox = [21, 585, 534, 626]
        d.screenshot().crop(uiObjectBox).save('lastorder_%s.png' % device[0])
        time.sleep(0.3)
        img = Image.open('lastorder_%s.png' % device[0])
        custom_config = '--oem 3 --psm 6 -l chi_sim+eng -c tessedit_char_whitelist=HMIS.0123456789'
        content = pytesseract.image_to_string(img, config=custom_config)
        content = content.replace('\n', '')
        content = content.split(' ')
        content = [x for x in content if x]
    except:
        pass  # postinserted
    time.sleep(1)
    d(text='持仓').click()
    logger.exception('设备 %s 执行最后一手识别发生错误' % device[0])
    return 1
            logger.info(f'{device[0]} :    最新成交数据识别：{content}')
            if '没有' in content or len(content) == 0:
                logger.info(f'{device[0]} :    没有最新成交数据！')
                return 1
            uiObjectBox = [296, 585, 405, 626]
            tesseract_config = '--oem 3 --psm 6 outputbase digits -'
            d.screenshot().crop(uiObjectBox).save('lastorder_0%s.png' % device[0])
            time.sleep(0.3)
            shoushu = pytesseract.image_to_string(d.screenshot().crop(uiObjectBox), config=tesseract_config)
            shoushu = shoushu.replace('\n', '')
            logger.info(f'{device[0]} :    最后成交手数为：{shoushu}')
            d.click(462, 465)
            time.sleep(5)
            d.drag(205, 700, 435, 700, 0.05)
            d.drag(205, 700, 435, 700, 0.05)
            time.sleep(1)
            d.drag(495, 700, 180, 700, 0.05)
            time.sleep(1)
            uiObjectBox = [380, 582, 490, 626]
            d.screenshot().crop(uiObjectBox).save('lastorder_1%s.png' % device[0])
            time.sleep(0.3)
            img = Image.open('lastorder_1%s.png' % device[0])
            tesseract_config = '--oem 3 --psm 6 outputbase digits -'
            yk = pytesseract.image_to_string(img, config=tesseract_config)
            yk = yk.replace('\n', '')
            yk = yk.replace(' ', '')
            logger.info(f'{device[0]} :    最新成交盈亏为：{yk}')
            if float(yk) < 0:
                logger.info(f'{device[0]} :    最新成交盈亏为负值，亏损！')
                zyzs = '止损'
            else:  # inserted
                logger.info(f'{device[0]} :    最新成交盈亏为正值，盈利！')
                zyzs = '止盈'
            print(f'{content[0]},{content[2]}')
            if 'MHI' in content[0]:
                future = '小恒指期货'
            else:  # inserted
                future = '恒指期货'
            direction = ''
            last_position = {'direction': direction, 'future': future, 'num': int(shoushu), 'index': 0}
            now_round = 0
            for item in strategy_list:
                if last_position['future'] == item['future'] and last_position['num'] == item['num']:
                    pass  # postinserted
                else:  # inserted
                    now_round = item['round']
            else:  # inserted
                logger.warning(f"{device[0]}  {time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())}  当前最后一次平仓为：{last_position}, {zyzs} ,第{now_round}口")
                now_round = now_round + 1 if float(yk) < 0 else logger.info(f'{device[0]} :    最新成交盈亏为正值，盈利！') or 1

def pytesseract_pcyk(d, device_id):
    """解析平仓盈亏数字"""  # inserted
    try:
        uiObjectBox = [177, 138, 365, 165]
        d.screenshot().crop(uiObjectBox).save('pcyk_%s.png' % device_id)
        time.sleep(0.3)
        content = pytesseract.image_to_string(d.screenshot().crop(uiObjectBox), config='--oem 3 --psm 6 -l chi_sim')
        content = content.replace('\n', '')
        content = content.split(':')
        content = content[1]
        return float(content)
    except:
        return 0

def pytesseract_total_amount(d, device_id):
    """解析权益金总金额数字"""  # inserted
    try:
        uiObjectBox = [50, 105, 150, 135]
        d.screenshot().crop(uiObjectBox).save('total_amount_%s.png' % device_id)
        time.sleep(0.3)
        content = pytesseract.image_to_string(d.screenshot().crop(uiObjectBox), config='--oem 3 --psm 6 -l chi_sim')
        content = content.replace('\n', '')
        return float(content)
    except:
        return 0

def pytesseract_commission_amount(d, device_id):
    """解析手续费总金额数字"""  # inserted
    try:
        uiObjectBox = [388, 137, 535, 162]
        d.screenshot().crop(uiObjectBox).save('commission_amount_%s.png' % device_id)
        time.sleep(0.3)
        content = pytesseract.image_to_string(d.screenshot().crop(uiObjectBox), config='--oem 3 --psm 6 -l chi_sim')
        content = content.replace('\n', '')
        content = content.split(':')
        content = content[1]
        return float(content)
    except:
        return 0

def pytesseract_fdyk(d, device_id):
    """解析浮动盈亏数字"""  # inserted
    try:
        uiObjectBox = [83, 140, 186, 159]
        tesseract_config = '--oem 3 --psm 6 outputbase digits -'
        d.screenshot().crop(uiObjectBox).save('fdyk_%s.png' % device_id)
        time.sleep(0.3)
        content = pytesseract.image_to_string(d.screenshot().crop(uiObjectBox), config=tesseract_config)
        content = content.replace('\n', '')
        return float(content)
    except:
        return 0

def pytesseract_new(d, device_id):
    """解析实时指数数字"""  # inserted
    try:
        pass
        uiObjectBox = [352, 184, 441, 222]
        tesseract_config = '--oem 3 --psm 6 outputbase digits -'
        content = pytesseract.image_to_string(d.screenshot().crop(uiObjectBox).convert('L'), config=tesseract_config)
        content = content.replace('\n', '')
        zs = float(content)
        return zs
    except:
        return (-1)

def find_image(image_origin, image_template, threshold, bgremove):
    match_result = ac.find_template(image_origin, image_template, threshold, bgremove)
    return match_result

def get_device_apps(d, device_id):
    installed_apps = d.app_list()
    for app in installed_apps:
        print(app)

def process_check(process_list):
    logname = 'process_check_log.txt'
    logger.add(logname, encoding='utf-8')
    while True:
        logger.info('进程监控中...')
        for p in process_list:
            if not p.is_alive():
                p.start()
                time.sleep(random.randint(3, 8))
                logger.warning(f'{p.name} 进程异常终止，已重启！')
        time.sleep(10)

def update_show():
    db1 = sqlite3.connect('db.sqlite3')
    cursor1 = db1.cursor()
    cursor1.execute('select * from user')
    users = cursor1.fetchall()
    tree.tag_configure('red_text_tag', foreground='red')
    tree.tag_configure('green_text_tag', foreground='green')
    for dr in users:
        for item in tree_rowids:
            if item['userid'] == dr[0] and dr[11] == '在线':
                tree.set(item['rowid'], '平仓盈亏', dr[7])
                tree.set(item['rowid'], '浮动盈亏', dr[6])
                tree.set(item['rowid'], '状态', dr[11])
                tree.set(item['rowid'], '账户金额', dr[5])
                tree.set(item['rowid'], '成交指数', dr[17])
                tree.set(item['rowid'], '手续费', dr[8])
                tree.set(item['rowid'], '轮/次', f'第{dr[15]}轮，第{dr[16]}次')
                now_time = datetime.datetime.now()
                edittime = datetime.datetime.strptime(dr[14], '%Y-%m-%d %H:%M:%S')
                delta = now_time - edittime
                seconds = delta.total_seconds()
                if seconds > 60:
                    tree.set(item['rowid'], '更新时间', f'{int(seconds / 60)}分前')
                else:  # inserted
                    tree.set(item['rowid'], '更新时间', f'{int(seconds)}秒前')
                if dr[6] >= 0:
                    tree.item(item['rowid'], tags=('red_text_tag',))
                else:  # inserted
                    if dr[6] < 0:
                        tree.item(item['rowid'], tags=('green_text_tag',))
                break
    db1.close()
    root.after(2000, update_show)

def button_stop():
    selected_items = tree.selection()
    for item in selected_items:
        item_attributes = tree.item(item, 'values')
        print(item_attributes, item_attributes[1])
    user_id = item_attributes[1]
    if item_attributes[4] == '已启动':
        for p in process_list:
            if p.name == user_id:
                p.terminate()
                tree.set(item_attributes[0], '脚本', '未启动')
                process_list.remove(p)
                print(f'{p.name} 进程已终止！')
                btnStart.grid(row=2, column=5)
                btnStop.grid_forget()

def button_start():
    selected_items = tree.selection()
    for item in selected_items:
        item_attributes = tree.item(item, 'values')
        print(item_attributes, item_attributes[1])
    user_id = item_attributes[1]
    if item_attributes[4] == '未启动':
        cursor.execute('select * from user where user_login_id=?', (user_id,))
        users = cursor.fetchall()
        dr = users[0]
        p = Process(target=Device_connect, args=(dr,), name=dr[0])
        p.daemon = True
        p.start()
        time.sleep(1)
        process_list.append(p)
        tree.set(item_attributes[0], '脚本', '已启动')
        logger.info('进程' + dr[0] + '已启动！')
        btnStart.grid_forget()
        btnStop.grid(row=2, column=5)

def button_clicked(event):
    item = tree.selection()[0]
    button_text = tree.item(item, 'values')[0]
    print(f'Button clicked with text: {button_text}')

def on_row_click(event):
    if tree.selection():
        for item in tree.selection():
            tree.selection_remove(item)
        tree.selection_add(event.widget.focus())
    selected_items = tree.selection()
    for item in selected_items:
        item_attributes = tree.item(item, 'values')
        print(item_attributes, item_attributes[1])
    if item_attributes[4] == '已启动':
        btnStart.grid_forget()
        btnStop.grid(row=2, column=5)
    else:  # inserted
        btnStart.grid(row=2, column=5)
        btnStop.grid_forget()
if __name__ == '__main__':
    engine = pyttsx3.init()
    engine.setProperty('voice', 'com.microsoft.speech.platform.voice.SynthesizerVoice')
    engine.setProperty('rate', 130)
    engine.setProperty('volume', 0.8)
    logger.info('开始检索在线模拟器...')
    devices = []
    db = sqlite3.connect('db.sqlite3')
    cursor = db.cursor()
    cursor.execute('update user set device_index=\'\',device_id=\'\',device_status=\'\',user_floating=0,user_now_amount=0,rounds_count=0,round=0,user_total_amount=0,user_commission=0,user_price_index=0')
    db.commit()
    cursor.execute('select * from user')
    users = cursor.fetchall()
    root = tk.Tk()
    root.title('账号列表')
    tree_rowids = []
    columns = ('行编号', '账号', '类型', '姓名', '脚本', '状态', '账户金额', '成交指数', '浮动盈亏', '平仓盈亏', '手续费', '轮/次', '更新时间')
    tree = ttk.Treeview(root, columns=columns, show='headings')
    for col in columns:
        tree.heading(col, text=col)
        tree.column(col, width=100)
    tree.grid(row=1, column=1, columnspan=10, sticky='nsew')
    for dr in users:
        rowid = tree.insert('', 'end', values=('', dr[0], dr[2], dr[3], dr[10], dr[11], 0, 0, 0, 0, 0, '-/-', '-'))
        tree.set(rowid, '行编号', rowid)
        tree_rowids.append({'rowid': rowid, 'userid': dr[0]})
    tree.bind('<ButtonRelease-1>', on_row_click)
    try:
        local_devices = []
        result = subprocess.run(['ldconsole', 'list2'], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
        for dr in users:
            is_exist = False
            for line in result.stdout.splitlines():
                value = line.split('\t')[0]
                dv = value.split(',')
                if dv[1] == dr[0]:
                    if int(dv[2]) > 0:
                        cursor.execute('update user set device_index=?,device_status=\'已启动\',edittime=? where user_login_id=? and user_type=?', (dv[0], time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()), dr[0], dr[2]))
                        db.commit()
                        local_devices.append({'login_id': dr[0], 'index': dv[0], 'name': dr[3], 'type': dr[2], 'device_id': '', 'status': '已启动'})
                    else:  # inserted
                        cursor.execute('update user set device_index=?,device_status=\'未启动\',edittime=? where user_login_id=? and user_type=?', (dv[0], time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()), dr[0], dr[2]))
                        db.commit()
                        local_devices.append({'login_id': dr[0], 'index': dv[0], 'name': dr[3], 'type': dr[2], 'device_id': '', 'status': '未启动'})
                    is_exist = True
            if not is_exist:
                pass  # postinserted
        except:
            print(traceback.format_exc())
                local_devices.append({'login_id': dr[0], 'index': '', 'name': dr[3], 'type': dr[2], 'device_id': '', 'status': '不存在'})
                result = subprocess.run(['ldconsole', 'sortWnd'], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
                time.sleep(1)
                try:
                    result = subprocess.run(['adb', 'devices'], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
                    n = 0
                    for line in result.stdout.splitlines():
                        if 'List of devices' not in line and line!= '':
                            pass  # postinserted
    except:
        logger.error('检索模拟器失败！')
                        else:  # inserted
                            device_id = line.split('\t')[0]
                            port = device_id.split('-')[1]
                            index = (int(port) - 5554) / 2
                            if line.split('\t')[1] == 'offline':
                                cursor.execute('update user set device_id=?,device_status=\'离线\',edittime=? where device_index=?', (device_id, time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()), index))
                                db.commit()
                            if line.split('\t')[1] == 'device':
                                cursor.execute('update user set device_id=?,device_status=\'在线\',edittime=? where device_index=?', (device_id, time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()), index))
                                db.commit()
                            n = n + 1
                            cursor.execute('select * from user')
                            users = cursor.fetchall()
                            process_list = []
                            print('子进程开始启动....')
                            for dr in users:
                                if dr[11] == '在线':
                                    p = Process(target=Device_connect, args=(dr,), name=dr[0])
                                    p.daemon = True
                                    p.start()
                                    time.sleep(1)
                                    process_list.append(p)
                                    logger.info('进程' + dr[0] + '已启动！')
                                    for item in tree_rowids:
                                        if dr[0] == item['userid']:
                                            tree.set(item['rowid'], '脚本', '已启动')
                                else:  # inserted
                                    for item in tree_rowids:
                                        if dr[0] == item['userid']:
                                            tree.set(item['rowid'], '脚本', '未启动')
                            print('子进程启动完毕')
                            btnStart = tk.Button(root, text='启动选中项脚本', font=('宋体', 14), bg='red', fg='white', command=button_start)
                            btnStop = tk.Button(root, text='停止选中项脚本', font=('宋体', 14), bg='green', fg='white', command=button_stop)
                            logger.info('主进程启动完毕,启动页面刷新')
                            update_show()
                            root.mainloop()